package com.next

class Menu
{
    String name
    String title

    String url
    String icon

    Menu parent
    Integer orderNum
    Integer status
    //1:启用 2：禁用
    Date createdDate = new Date()
    Date modifiedDate = new Date()
    User createBy
    User modifyBy
    static hasMany = [children: Menu]
    static belongsTo = [parent: Menu]

    static transients = ['allChildren']

    def getAllChildren()
    {
        children ? children + children*.allChildren.flatten() : []
    }

    def shouldActive(String targetUrl)
    {
        if (targetUrl.indexOf(url) > -1)
        {
            return 'active'
        }
        children.each { cmenu ->
            if (targetUrl.indexOf(cmenu.url) > -1)
            {
                return 'active'
            }
        }
        return ''
    }
    def springSecurityService

    def beforeInsert()
    {
        def username = springSecurityService?.getPrincipal()?.username
        createBy = User.findByUsername(username)
    }

    def beforeUpdate()
    {
        modifiedDate = new Date()
        def username = springSecurityService?.getPrincipal()?.username
        modifyBy = User.findByUsername(username)
    }

    static constraints = {
        name maxSize: 32, unqiue: true
        title blank: false, unique: true, maxSize: 32
        url blank: true, nullable: true, maxSize: 64
        icon blank: true, nullable: true, maxSize: 64
        parent blank: true, nullable: true
        orderNum blank: true, nullable: true
        status blank: true, nullable: true
        createBy blank: true, nullable: true
        createdDate blank: true, nullable: true
        modifyBy blank: true, nullable: true
        modifiedDate blank: true, nullable: true
    }

    static mapping = {
        sort orderNum: 'asc'

    }
}
